import { memo, ReactElement, useState, useCallback, useRef } from "react";
import type { FC } from "react";

import styles from "./index.module.scss";
import classNames from "classnames";
import { ISuggestList } from "@/services/modules/home";
export interface IProps {
  children?: ReactElement;
  suggestList?: ISuggestList;
}

const Search: FC<IProps> = memo(function (props) {
  const { children, suggestList } = props;
  const [searchMsg, setSearchMsg] = useState("");
  const [sPanelVis, setSPanelVis] = useState<boolean>(false);

  const inputRef = useRef<any>(null);
  const handleSearchVis = (vis: boolean) => {
    setSPanelVis(vis);
  };

  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent) => {
      if (event.key === "Enter") {
        // 执行一些操作，比如打印输入框的值
        console.log("You pressed Enter in the input field:", searchMsg);
      }
    },
    [searchMsg]
  );

  const handleClick = (val: string) => {
    console.log(val);
    setSearchMsg(val);

    setTimeout(() => {
      inputRef.current?.focus();
      // 使用 setTimeout 确保 DOM 更新后执行
    }, 0);
  };
  return (
    <>
      <div className={styles.container}>
        <div className={styles["search-box"]}>
          <input
            ref={inputRef}
            className={styles["input"]}
            type="text"
            placeholder="蓝牙耳机"
            value={searchMsg}
            onChange={(e) => setSearchMsg(e.target.value)}
            onFocus={() => handleSearchVis(true)}
            onBlur={() => handleSearchVis(false)}
            onKeyDown={handleKeyDown}
          ></input>
        </div>
        <div
          className={classNames(
            styles["search-panel"],
            sPanelVis && styles["show"]
          )}
        >
          <div className={styles.shadow}></div>
          <h2 className={styles.title}>热门搜索</h2>
          <ul>
            {suggestList?.configKey &&
              suggestList?.configKey.map((item, index) => {
                return (
                  <li
                    key={item[index + 1]}
                    onMouseDown={() => handleClick(item[index + 1])}
                  >
                    {item[index + 1]}
                  </li>
                );
              })}
          </ul>
        </div>
      </div>
    </>
  );
});

export default Search;
Search.displayName = "Search";
